<#
    .AUTHOR
        cw50406@imcnam.ssmb.com  
    .GROUP
        RPA AA STE Support Team(dl.gt.cn.cstc.rpa.aa.ste@imcnam.ssmb.com)
    .VERSION
        2.0
    .Synopsis
        Control Room Website Auto Login trigger with Task scheduler
    .DESCRIPTION
        This script is used to trigger WebsiteAutoLogin by specified different parames
    .EXAMPLE
        .\master.ps1
#>
[CmdletBinding()]param(
    [Parameter(Mandatory=$false)]
    [string]$rdc_login_user='nam\aaadmin'
)
$this_path = Split-Path -Parent ($MyInvocation.MyCommand.Definition)
. "$this_path\functions.ps1"  #<-------------------------------- initilize parames, functions & .NET assembles
Write-Log Normal "----------------------------START OF SCRIPT----------------------------" $log_file
write-log Normal "Trying to get RDC login user credentials($rdc_login_user)" $log_file
$rdc_login_user_domain,$rdc_login_user=Get-LoginUser $PSBoundParameters.ContainsKey('rdc_login_user') $rdc_login_user
$autosys_out_log,$autosys_err_log|%{New-FileOrFolder $_}
write-log Normal "Adding RDC login user access to autosys log file" $log_file
$log_file,$autosys_out_log |%{Set-FileAccess $_ "$rdc_login_user_domain\$rdc_login_user"}
If( ($startup_files=(dir "C:\Users\$rdc_login_user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" -ea 0).Name) -ne $null){
    write-log Normal "Move out RDC login user startup folder files" $log_file
    $startup_files|%{move-item "C:\Users\$rdc_login_user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\$_" "$this_path\" -force -ea 0}
}
If( ((quser $rdc_login_user 2>$null) -imatch 'active')){ # Try to find if the user has logged in this server
    Write-Log Success "Found active user $rdc_login_user in $this_machine" $log_file ; $found_login_user=$true
}
write-log Normal "Trying to get $rdc_login_user password for CR website login" $log_file
If( ($rdc_login_user_pwd=[CredentialValidate.GetPassword]::ReturnLoginPWD()) -eq $null ){
    Stop-WithError "Not get $rdc_login_user password"
}elseif(! (Validate-Credential "$rdc_login_user_domain\$rdc_login_user" $rdc_login_user_pwd $log_file )){
    Stop-WithError "Invalid $rdc_login_user password: $rdc_login_user_pwd"
}
if(!$found_login_user){ # remove login OK button (no person will click the OK button) and then login this vm in this user session
    try{ # remove login ok button and add credentils
        write-log Normal 'Removing login ok button' $log_file
        reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system\"  /v legalnoticecaption /f 2>$null
        reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system\"  /v legalnoticetext /f 2>$null
        cmdkey.exe /generic:$this_machine /user:$rdc_login_user_domain\$rdc_login_user /pass:$rdc_login_user_pwd 1>$null 2>&1
    }catch{Write-Log Error $_ $log_file}
    try{
        write-log Normal "Trying to login $this_machine in user $rdc_login_user session" $log_file
        mstsc.exe /v $this_machine 1>$null 2>&1 ; $loop_cnt=0
        Do{ # loop to find if $rdc_login_user has logged in $this_machine
            $rst=((quser $rdc_login_user 2>$null) -imatch 'active') ; sleep 5
            If( $loop_cnt++ -gt 59 ){
                Send-Mailtoteam 'Error' $log_file; exit
            }
        }While([string]::IsNullOrWhiteSpace($rst))
        Write-Log Success "User $rdc_login_user has now logged in $this_machine" $log_file
    }catch{Stop-WithError ": Unhandled Error"}
}
SCHTASKS /CREATE /RU "$rdc_login_user_domain\$rdc_login_user" /tn 'CRWebsiteLogin' /sc ONCE  /st (get-date).tostring("HH:mm") /F `
/tr "powershell.exe -WindowStyle Hidden -Executionpolicy unrestricted '$this_path\CRWebsiteLogin.ps1 $rdc_login_user_domain\$rdc_login_user $rdc_login_user_pwd $log_file'" 1>$null 2>&1
If( SCHTASKS /QUERY /TN 'CRWebsiteLogin' 2>$null ){
    SCHTASKS /run /TN 'CRWebsiteLogin' 1>$null 2>&1 ; $loop_cnt=0
    sleep 240
    Do{
        If( (SCHTASKS /QUERY /TN 'CRWebsiteLogin' 2>$null) -imatch "Ready" ){
            break
        }
        If( $loop_cnt++ -gt 355){
            write-log Error 'Task CRWebsiteLogin is still runnin after 10 mins' $log_file
            break
        }sleep 5
    }While( 1 )
}
SCHTASKS /delete /TN 'CRWebsiteLogin' /F 1>$null 2>&1
If( $startup_files -ne $null ){
    write-log Normal "Move back files to RDC login user startup folder" $log_file
    $startup_files|%{move-item "$this_path\$_" "C:\Users\$rdc_login_user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\" -force -ea 0}
}
